package com.sangeng.service.impl;

import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.vo.BlogUserLoginVo;
import com.sangeng.domain.vo.UserInfoVo;
import com.sangeng.service.BlogLoginService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


import java.util.Objects;

/**
 * @auther qihs
 * @Date
 */
@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    //注入验证接口，需要在实现类将该接口注入到容器中
    @Autowired
    private AuthenticationManager authenticationManager;
    //注入RedisCache工具类
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //获取Authentication对象，并将用户名与密码传入
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //会调用UserDetailsService方法，进行校验
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //获UserDetails验证体，强转为LoginUser
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取UserId ,生成token   JwtUtil：定义的jwt生成工具类
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //将用户信息存入Redis；  key中字符拼接自由写
        redisCache.setCacheObject("bloglogin:"+userId, loginUser);
        //封装User信息为UserInfoVo    此处注意loginUser是验证体，需要获取到user
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        //封装、返回用户信息
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt, userInfoVo);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        //获取token，解析获取userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //根据ID，删除redis中的数据
        redisCache.deleteObject("bloglogin:"+userId);
        //响应退出登录请求
        return ResponseResult.okResult();
    }

}
